package com.haocang.szgm.ui.floodpoint.activity;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.core.geometry.Point;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.comm.CommMapFinalActivity;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.commonlib.network.interfaces.InitDataCallBack;
import com.haocang.szgm.ui.floodpoint.bean.FloodPointBean;
import com.haocang.szgm.ui.tools.activity.MultiSelectDialog;
import com.haocang.szgm.utils.bean.ProvinceBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.szgm.utils.config.WebApi;
import com.haocang.commonlib.loadingdialog.LoadingDialog;
import com.haocang.szgm.utils.tools.CacheData;
import com.haocang.szgm.utils.tools.MyTextUtils;
import com.haocang.szgm.utils.tools.OptionsItemsUtils;

import net.tsz.afinal.annotation.view.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class FloodPointDeatilActivity extends CommMapFinalActivity {


    @ViewInject(id = R.id.fd_1)
    EditText fd_1;
    @ViewInject(id = R.id.fd_2)
    EditText fd_2;
    @ViewInject(id = R.id.fd_3)
    TextView fd_3;
    @ViewInject(id = R.id.fd_4)
    EditText fd_4;
    @ViewInject(id = R.id.fd_5)
    EditText fd_5;
    @ViewInject(id = R.id.fd_6)
    EditText fd_6;
    @ViewInject(id = R.id.fd_7)
    EditText fd_7;
    @ViewInject(id = R.id.fd_8)
    EditText fd_8;
    @ViewInject(id = R.id.fd_9)
    EditText fd_9;
    @ViewInject(id = R.id.fd_10)
    EditText fd_10;
    @ViewInject(id = R.id.fd_11)
    EditText fd_11;
    @ViewInject(id = R.id.fd_12)
    EditText fd_12;

    @ViewInject(id = R.id.char_Keyboard)
    LinearLayout char_Keyboard;

    @ViewInject(id = R.id.floodpoint_submit)
    Button floodpoint_submit;
    private LoadingDialog dialog;
    private FloodPointBean model;

    protected GraphicsLayer gsLayerPos;//自定义图层

    private String isActive = "Y";//有效性



    private ArrayList<MultiSelectDialog.OnSoftKeyboardStateChangedListener> mKeyboardStateListeners = new ArrayList<>();      //软键盘状态监听列表
    private ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener;
    private boolean mIsSoftKeyboardShowing = false;
    public interface OnSoftKeyboardStateChangedListener {
        public void OnSoftKeyboardStateChanged(boolean isKeyBoardShow, int keyboardHeight);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gsLayerPos = new GraphicsLayer();
        mMapView.addLayer(gsLayerPos);
        initEvent();

        if (CacheData.FloodPoint_UPDATE) {
            initData();
        }

    }


    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_flood_point_deatil;
    }

    @Override
    protected boolean showNavigation() {
        return true;
    }

    @Override
    protected boolean showMedia() {
        return false;
    }

    @Override
    protected int showMoreIcon() {
        return 0;
    }

    @Override
    protected String showTitleName() {
        return "易淹点";
    }

    @Override
    protected boolean showMapPipe() {
        return false;
    }

    private void initEvent() {

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });


        floodpoint_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initSubmit();
            }
        });

        fd_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDeviceCode(OptionsItemsUtils.GetFloodPointType(),1);
            }
        });

        mMapView.setOnSingleTapListener(new OnSingleTapListener() {

            @Override
            public void onSingleTap(float x, float y) {

                Point mapPoint = mMapView.toMapPoint(x, y);
                SingleTap_X = mapPoint.getX();
                SingleTap_Y = mapPoint.getY();
                addpoint(mapPoint);

            }
        });


        mLayoutChangeListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                WindowManager manager = FloodPointDeatilActivity.this.getWindowManager();
                DisplayMetrics outMetrics = new DisplayMetrics();
                manager.getDefaultDisplay().getMetrics(outMetrics);
                int screenWidth = outMetrics.widthPixels;
                int screenHeight = outMetrics.heightPixels;

                //判断窗口可见区域大小
                Rect r = new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3，则表示软键盘显示中，否则软键盘为隐藏状态。
                int heightDifference = screenHeight - (r.bottom - r.top);
                boolean isKeyboardShowing = heightDifference > screenHeight / 3;

                //如果之前软键盘状态为显示，现在为关闭，或者之前为关闭，现在为显示，则表示软键盘的状态发生了改变
                if ((mIsSoftKeyboardShowing && !isKeyboardShowing) || (!mIsSoftKeyboardShowing && isKeyboardShowing)) {
                    mIsSoftKeyboardShowing = isKeyboardShowing;
                    LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) char_Keyboard.getLayoutParams();

                    if (mIsSoftKeyboardShowing) {
                        linearParams.height = heightDifference - 60;
                    } else {
                        linearParams.height = 0;
                    }
                    char_Keyboard.setLayoutParams(linearParams);

                    for (int i = 0; i < mKeyboardStateListeners.size(); i++) {
                        MultiSelectDialog.OnSoftKeyboardStateChangedListener listener = mKeyboardStateListeners.get(i);
                        listener.OnSoftKeyboardStateChanged(mIsSoftKeyboardShowing, heightDifference);
                    }
                }
            }
        };
        //注册布局变化监听
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);

    }


    private void initData() {

        model = CacheData.mFloodPointBean;

        fd_1.setText(model.getSeepeNo());
        fd_2.setText(model.getYear());
        fd_3.setText(MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetFloodPointType(),1,model.getType()));
        fd_4.setText(model.getLocation());
        fd_5.setText(model.getManagementOffice());
        fd_6.setText(model.getStreetOperation());
        fd_7.setText(model.getCommunity());
        fd_8.setText(model.getRoad());
        fd_9.setText(model.getFloodUser());
        fd_10.setText(model.getDistrictPhone());
        fd_11.setText(model.getSeeperReason());
        fd_12.setText(model.getMemo());
        isActive = model.getIsActive();

        SingleTap_X = model.getX();
        SingleTap_Y = model.getY();
        addpoint(new Point(SingleTap_X, SingleTap_Y));

    }


    private void initSubmit() {



        String SeepeNo = fd_1.getText().toString();
        String Year = fd_2.getText().toString();
        String Type = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetFloodPointType(),0,fd_3.getText().toString());
        String Location = fd_4.getText().toString();
        String ManagementOffice = fd_5.getText().toString();
        String StreetOperation = fd_6.getText().toString();
        String Community = fd_7.getText().toString();
        String Road = fd_8.getText().toString();
        String FloodUser = fd_9.getText().toString();
        String DistrictPhone = fd_10.getText().toString();
        String SeeperReason = fd_11.getText().toString();
        String Memo = fd_12.getText().toString();

        if (SingleTap_X == 0 || SingleTap_Y == 0) {
            ToastShow("请设置坐标");
            return;
        }

        if (MyTextUtils.IsNullByString(SeepeNo)) {
            ToastShow("编号不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(Year)) {
            ToastShow("年份不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(Type)) {
            ToastShow("类型不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(Location)) {
            ToastShow("地点不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(ManagementOffice) || MyTextUtils.IsNullByString(StreetOperation)
                || MyTextUtils.IsNullByString(Community) || MyTextUtils.IsNullByString(Road)) {
            ToastShow("管理所、街道办，社区，道路地点不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(SeeperReason)) {
            ToastShow("积水原因不能为空");
            return;
        }

        HashMap<String, Object> maps = new HashMap<>();
        if (CacheData.FloodPoint_UPDATE) {
            maps.put("ID", model.getID());
        }
        maps.put("SeepeNo", SeepeNo);
        maps.put("Year", Year);
        maps.put("Type", Type);
        maps.put("Location", Location);
        maps.put("X", SingleTap_X);
        maps.put("Y", SingleTap_Y);
        maps.put("ManagementOffice", ManagementOffice);
        maps.put("StreetOperation", StreetOperation);
        maps.put("Community", Community);
        maps.put("Road", Road);
        maps.put("FloodUser", FloodUser);
        maps.put("DistrictPhone", DistrictPhone);
        maps.put("SeeperReason", SeeperReason);
        maps.put("Memo", Memo);
        maps.put("IsActive", isActive);
        maps.put("IsHandle", "");

        dialog = new LoadingDialog(FloodPointDeatilActivity.this, "保存中");
        dialog.show();
        DataModel.PostApiRequest(mContext, Config.host + WebApi.Api_PostFloodPoint, maps, new InitDataCallBack() {

            @Override
            public void callbak(boolean b, String string) {

                if (b) {
                    Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
                    finish();
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                } else {
                    Toast.makeText(mContext, "保存失败" + string, Toast.LENGTH_SHORT).show();
                }
                dialog.close();
            }
        });
    }


    private void chooseDeviceCode(final List<ProvinceBean> items, final int pos) {
        OptionsPickerView.Builder builder = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String itemName = items.get(options1).getPickerViewText();
                switch (pos) {
                    case 1:
                        fd_3.setText(itemName);
                        break;
                }
            }
        });
        OptionsPickerView<ProvinceBean> pickerView = new OptionsPickerView<>(builder);
        pickerView.setPicker(items);
        pickerView.show();
    }
    //退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            return super.onKeyDown(keyCode, event);
        }else{
            return  false;
        }
    }

}
